import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { X, Save, Info } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";

const towerTypeLabels = {
  tensionTower: "耐张塔",
  straightLineTower: "直线塔",
  angleTower: "转角塔",
  branchTower: "分支塔",
};

export default function TowerForm({
  tower,
  projects,
  tensionSections = [],
  onSubmit,
  onCancel,
}) {
  const [formData, setFormData] = useState({
    projectId: "",
    towerNumber: "",
    type: "straightLineTower",
    height: "",
    groundElevation: "",
    latitude: "",
    longitude: "",
    spanToNextTower: "", // Added new field
    description: "",
    insulatorStringLength: "",
    distanceToRoad: "",
  });

  const [relatedTensionSections, setRelatedTensionSections] = useState([]);

  useEffect(() => {
    if (tower) {
      // When editing an existing tower, populate all fields, including the new one.
      setFormData({
        projectId: tower.projectId || "",
        towerNumber: tower.towerNumber || "",
        type: tower.type || "straightLineTower",
        height:
          tower.height !== null && tower.height !== undefined
            ? String(tower.height)
            : "",
        groundElevation:
          tower.groundElevation !== null && tower.groundElevation !== undefined
            ? String(tower.groundElevation)
            : "",
        latitude:
          tower.latitude !== null && tower.latitude !== undefined
            ? String(tower.latitude)
            : "",
        longitude:
          tower.longitude !== null && tower.longitude !== undefined
            ? String(tower.longitude)
            : "",
        spanToNextTower:
          tower.spanToNextTower !== null && tower.spanToNextTower !== undefined
            ? String(tower.spanToNextTower)
            : "", // Initialize new field
        description: tower.description || "",

        insulatorStringLength: tower.insulatorStringLength || "",
        distanceToRoad: tower.distanceToRoad || "",
      });
    } else if (projects && projects.length > 0) {
      setFormData((prev) => ({ ...prev, projectId: projects[0].id }));
    }
  }, [tower, projects]);

  // 查找包含此杆塔的勘查单（只读显示）
  useEffect(() => {
    if (tower && tower.id && tensionSections) {
      const related = tensionSections.filter(
        (ts) =>
          ts.startTensionTowerId === tower.id ||
          ts.endTensionTowerId === tower.id ||
          (ts.intermediateTowerIds &&
            ts.intermediateTowerIds.includes(tower.id))
      );
      setRelatedTensionSections(related);
    } else {
      setRelatedTensionSections([]);
    }
  }, [tower, tensionSections]);

  const handleChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    const data = {
      ...formData,
      // Convert numeric fields to float or null
      height:
        formData.height === "" ? null : parseFloat(formData.height) || null,
      groundElevation:
        formData.groundElevation === ""
          ? null
          : parseFloat(formData.groundElevation) || null,
      latitude:
        formData.latitude === "" ? null : parseFloat(formData.latitude) || null,
      longitude:
        formData.longitude === ""
          ? null
          : parseFloat(formData.longitude) || null,
      spanToNextTower:
        formData.spanToNextTower === ""
          ? null
          : parseFloat(formData.spanToNextTower) || null, // Handle new field
    };

    onSubmit(data);
  };

  return (
    <Card className="mb-6 shadow-lg border-0">
      <CardHeader className="bg-gradient-to-r from-purple-50 to-pink-50 border-b">
        <CardTitle className="flex items-center justify-between">
          <span>{tower ? "编辑杆塔" : "新建杆塔"}</span>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 所属勘查单显示（只读） */}
          {tower && relatedTensionSections.length > 0 && (
            <Alert className="bg-purple-50 border-purple-200">
              <Info className="h-4 w-4 text-purple-600" />
              <AlertDescription className="text-purple-800">
                <p className="font-medium mb-2">此杆塔已被以下勘查单引用：</p>
                <div className="flex flex-wrap gap-2">
                  {relatedTensionSections.map((ts) => (
                    <Badge key={ts.id} variant="outline" className="bg-white">
                      {ts.name}
                      {ts.startTensionTowerId === tower.id && (
                        <span className="ml-1 text-xs">(起始塔)</span>
                      )}
                      {ts.endTensionTowerId === tower.id && (
                        <span className="ml-1 text-xs">(结束塔)</span>
                      )}
                      {ts.intermediateTowerIds &&
                        ts.intermediateTowerIds.includes(tower.id) && (
                          <span className="ml-1 text-xs">(中间塔)</span>
                        )}
                    </Badge>
                  ))}
                </div>
                <p className="text-xs mt-2 text-purple-600">
                  如需修改勘查单关联，请前往"勘察单管理"页面操作
                </p>
              </AlertDescription>
            </Alert>
          )}

          {/* 基本信息 */}
          <div className="space-y-4">
            <h3 className="font-semibold text-lg border-b pb-2">基本信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="projectId">所属项目 *</Label>
                <Select
                  value={formData.projectId}
                  onValueChange={(value) => handleChange("projectId", value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择项目" />
                  </SelectTrigger>
                  <SelectContent>
                    {projects &&
                      projects.map((p) => (
                        <SelectItem key={p.id} value={p.id}>
                          {p.projectName}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="towerNumber">杆塔编号 *</Label>
                <Input
                  id="towerNumber"
                  value={formData.towerNumber}
                  onChange={(e) => handleChange("towerNumber", e.target.value)}
                  placeholder="如: 1号杆"
                  required
                />
              </div>

              <div>
                <Label htmlFor="type">杆塔类型 *</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value) => handleChange("type", value)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(towerTypeLabels).map(([key, label]) => (
                      <SelectItem key={key} value={key}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="height">杆塔高度 (m)</Label>
                <Input
                  id="height"
                  type="number"
                  step="0.1"
                  value={formData.height}
                  onChange={(e) => handleChange("height", e.target.value)}
                  placeholder="输入杆塔高度"
                />
              </div>
              <div>
                <Label htmlFor="spanToNextTower">
                  到下一杆塔的档距 (m)
                  <span className="text-xs text-gray-500 ml-2">
                    即本杆塔到下一杆塔之间的距离
                  </span>
                </Label>
                <Input
                  id="spanToNextTower"
                  type="number"
                  step="0.1"
                  value={formData.spanToNextTower}
                  onChange={(e) =>
                    handleChange("spanToNextTower", e.target.value)
                  }
                  placeholder="输入档距长度"
                />
              </div>
              <div>
                <Label htmlFor="groundElevation">呼称高</Label>
                <Input
                  id="groundElevation"
                  type="number"
                  step="0.1"
                  value={formData.groundElevation}
                  onChange={(e) =>
                    handleChange("groundElevation", e.target.value)
                  }
                  placeholder="输入档距长度"
                />
              </div>
              <div>
                <Label htmlFor="insulatorStringLength">杆塔绝缘子串长度</Label>
                <Input
                  id="insulatorStringLength"
                  type="number"
                  step="0.1"
                  value={formData.insulatorStringLength}
                  onChange={(e) =>
                    handleChange("insulatorStringLength", e.target.value)
                  }
                  placeholder="输入档距长度"
                />
              </div>
              {/* <div>
                <Label htmlFor="distanceToRoad">距被跨越物距离 (m)</Label>
                <Input
                  id="distanceToRoad"
                  type="number"
                  step="0.1"
                  value={formData.distanceToRoad}
                  onChange={(e) =>
                    handleChange("distanceToRoad", e.target.value)
                  }
                  placeholder="输入档距长度"
                />
              </div> */}
            </div>
          </div>

          {/* 地理位置 */}
          <div className="space-y-4">
            <h3 className="font-semibold text-lg border-b pb-2">地理位置</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="latitude">纬度</Label>
                <Input
                  id="latitude"
                  type="number"
                  step="0.000001"
                  value={formData.latitude}
                  onChange={(e) => handleChange("latitude", e.target.value)}
                  placeholder="输入纬度"
                />
              </div>

              <div>
                <Label htmlFor="longitude">经度</Label>
                <Input
                  id="longitude"
                  type="number"
                  step="0.000001"
                  value={formData.longitude}
                  onChange={(e) => handleChange("longitude", e.target.value)}
                  placeholder="输入经度"
                />
              </div>
            </div>
          </div>

          {/* 描述 */}
          <div>
            <Label htmlFor="description">描述</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => handleChange("description", e.target.value)}
              rows={3}
              placeholder="输入杆塔描述信息..."
            />
          </div>

          {/* 提交按钮 */}
          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="outline" onClick={onCancel}>
              取消
            </Button>
            <Button type="submit" className="bg-purple-600 hover:bg-purple-700">
              <Save className="w-4 h-4 mr-2" />
              {tower ? "更新杆塔" : "创建杆塔"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
